//
//  WBHomeViewController.swift
//  Swift微博
//
//  Created by 汪大强 on 2018/7/16.
//  Copyright © 2018年 汪大强. All rights reserved.
//

import UIKit
// 定义全部常量，尽量使用 private 修饰，否则到处都可以访问
private let cellId = "cellId"

class WBHomeViewController: WBBaseViewController {
    
    /// 列表视图模型
    private lazy var listViewModel = WBStatusListViewModel()
    
    // 微博数据源
    private lazy var statusList = [String]()
    
//    override func viewDidLoad() {
//        super.viewDidLoad()
//
//        // Do any additional setup after loading the view.
//    }
    
    /// 加载数据
    override func loadData() {
        
       
        print("准备刷新，最后一条 \(String(describing: self.listViewModel.statusList.last?.text))")
        listViewModel.loadStatus(pullup: self.isPullup) { (isSuccess, shouldRefresh) in
            print("加载数据结束 \(String(describing: self.listViewModel.statusList.last?.text))")
            // 结束刷新控件
            self.refreshControl?.endRefreshing()
            // 恢复上拉刷新标记
            self.isPullup = false
            // 刷新表格
            if shouldRefresh{
                 self.tableView?.reloadData()
            }
           
        }
    }
        
        /* 未使用微博网络请求封装分类
        // 用网络工具加载微博数据
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        let params = ["access_token":"2.00poruKG0C1mBCb6f962ca2dVYV5LD"]
        // 未封装前，直接调用
//        WBNetworkManager.shared.get(urlString, parameters: params, progress: nil, success: { (_, json) in
//            print(json as Any)
//        }) { (_, error) in
//            print("网络请求失败 \(error)")
//        }
        WBNetworkManager.shared.request(method: .GET, URLString: urlString, parameters: params as [String : AnyObject]) { (json, isSuccess) in
            print("封装后请求数据的结果\(json as AnyObject)")
        }
        */
        
        /* 未使用视图模型时
        WBNetworkManager.shared.statusList { (result, isSuccess) in
            // 字典转模型，绑定表格数据
            print("---------------------- \(result as Any)")
        }
        
        print("开始加载数据 \(WBNetworkManager.shared)")
        
        // 模拟 '延迟' 加载数据 -> dispatch_after
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            for i in 0..<15 {
                if self.isPullup {
                    // 将数据追加到底部
                    self.statusList.append("上拉 \(i)")
                }else{
                    // 将数据插入到数组的顶部
                    self.statusList.insert(i.description, at: 0)
                }
            }
            
            // 结束刷新控件
            self.refreshControl?.endRefreshing()
            // 恢复上拉刷新标记
            self.isPullup = false
            // 刷新表格
            self.tableView?.reloadData()
        }
        
//        for i in 0..<15 {
//            // 将数据插入到数组的顶部
//            statusList.insert(i.description, at: 0)
//        }
//        refreshControl?.endRefreshing()
//        tableView?.reloadData()
 
 */
    
    /// 显示好友
    @objc private func showFriends(){
        print(#function)
        let vc = WBDemoViewController()
        
        //vc.hidesBottomBarWhenPushed = true
        
        // push 的动作是 nav 做的
        navigationController?.pushViewController(vc, animated: true)
        
    }
}

// MARK: - 表格数据源方法，具体的数据源方法实现，不需要 super
extension WBHomeViewController{
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listViewModel.statusList.count
//        return statusList.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 1. 取 cell
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
        // 2. 设置 cell
        cell.textLabel?.text = listViewModel.statusList[indexPath.row].text
        
        // 3. 返回 cell
        return cell
        
    }
}

// MARK: - 设置界面
extension WBHomeViewController {
    /// 重写父类的方法
    override func setupTableView() {
        super.setupTableView()
        // 设置导航栏按钮
        // 无法高亮
        //navigationItem.leftBarButtonItem = UIBarButtonItem(title: "好友", style: .plain, target: self, action: #selector(showFriends))
        // Swift 调用 OC 返回 instancetype 的方法，判断不出是否可选（加一个类型可解决）
//        let btn: UIButton = UIButton.cz_textButton("好友", fontSize: 16, normalColor: UIColor.darkGray, highlightedColor: UIColor.orange)
//        btn.addTarget(self, action: #selector(showFriends), for: .touchUpInside)
//
//        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: btn)
        // 系统导航栏
//        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "好友", target: self, action: #selector(showFriends))
        
        // 自定义导航栏
        navItem.leftBarButtonItem = UIBarButtonItem(title: "好友", target: self, action: #selector(showFriends))
        
        // 注册原型 cell
//        tableView?.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
        tableView?.register(UINib(nibName: "WBStatusNormalCell", bundle: nil), forCellReuseIdentifier: cellId)
        
        setupNavTitle()
    }
    
    /// 设置导航栏标题
    private func setupNavTitle() {
        
        let button = WBTitleButton(title: (WBNetworkManager.shared.userAccount.screen_name ?? "") + " ")
        
        navItem.titleView = button
        
        
        button.addTarget(self, action: #selector(clickTitleButton), for: .touchUpInside)
    }
    
    @objc func clickTitleButton(btn: UIButton) {
        
        // 设置选中状态
        btn.isSelected = !btn.isSelected
        
    }
}
